package com.suncaper.han_yi_system.controller;

import com.suncaper.han_yi_system.pojo.dto.ApplicationQueryDto;
import com.suncaper.han_yi_system.pojo.vo.ApplicationStatsVo;
import com.suncaper.han_yi_system.result.Result;
import com.suncaper.han_yi_system.service.ApplicationService;
import com.suncaper.han_yi_system.service.ClothingStyleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/statistics")
@CrossOrigin(origins = "*")
@Tag(name = "统计管理")
@Slf4j
public class StatisticsController {

    @Autowired
    ApplicationService applicationService;

    @Autowired
    ClothingStyleService clothingStyleService;

    @Operation(summary = "获取统计信息")
    @PostMapping("/getStatistics")
    public Result getStatistics(@RequestBody ApplicationQueryDto applicationQueryDto) {

        ApplicationStatsVo applicationStats = applicationService.getApplicationStats(applicationQueryDto);

        Map<String, Object> clothingStats = clothingStyleService.getClothingStats(applicationQueryDto);

        return Result.ok().data("applicationStats", applicationStats)
                .data("clothingStats", clothingStats.get("clothingStatsVo"))
                .data("styleStats", clothingStats.get("styleStatsVos"));
    }

    @Operation(summary = "导出统计数据信息")
    @PostMapping("/export")
    public ResponseEntity<byte[]> exportStatistics(@RequestBody ApplicationQueryDto applicationQueryDto) throws Exception {

        try (XSSFWorkbook workbook = applicationService.exportStatistics(applicationQueryDto); ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            // 1. 将Workbook写入字节流
            workbook.write(outputStream);

            // 2. 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "Statistics_Report.xlsx"); // 文件名

            // 3. 返回ResponseEntity
            return new ResponseEntity<>(
                    outputStream.toByteArray(), // 文件字节数组
                    headers,
                    HttpStatus.OK
            );
        }
    }
}
